package edu.gatech.cs4400.spring2014.A8.control;

import java.sql.SQLException;

import javax.swing.JLabel;
import javax.swing.JPanel;

import edu.gatech.cs4400.spring2014.A8.model.ConnectionManager;
import edu.gatech.cs4400.spring2014.A8.view.ApplicationWindow;

/**
 * Application entry point
 * 
 * @author Stephen
 */
public abstract class Driver {
	
	/**
	 * Highest level execution of the application
	 * 
	 * @param args
	 * @throws SQLException 
	 */
	public static void main(String[] args) throws SQLException {
		//set up the application's window
		ApplicationWindow.initialize();
		
		//Provide a dialog for initial setup
		JPanel tempPanel = new JPanel();
		JLabel messageLabel = new JLabel("Attempting to connect to database");
		tempPanel.add(messageLabel);
		ApplicationWindow.addView(tempPanel, "StartupMessage");
		ApplicationWindow.setView("StartupMessage");
		
		//attempt to connect to the database
		if (!ConnectionManager.connect()) {
			messageLabel.setText("Failed to connect to database. Did you forget to connect to VPN?");
			return;
		}
		
		//Main program loop. Cycles between login and main operations.
		// A return from MainController.run() indicates a logout
		// Finally block ensures the connection to the database is closed properly
		try {
			while (true) {
					//Go to the login state
					LoginController login = new LoginController();
					login.run();
					MainController maincontrol = new MainController();
					maincontrol.run();
				
			}
		}
		finally {
			ConnectionManager.statement.close();
			ConnectionManager.connection.close();
		}
	}
}


